package com.bls.cate.mvp;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;

/**
 * MVPPlugin
 * 邮箱 784787081@qq.com
 */

public class BasePresenterImpl<V extends BaseView> implements BasePresenter<V> {
    protected V mView;

    @Override
    public void attachView(V view) {
        mView = view;
    }


    @Override
    public void detachView() {
        mView = null;
    }

    @Override
    public void requestGetNetData(final int requestId, String url, CacheMode cacheMode, HttpParams... httpParamsArray) {
        if (mView == null)
            return;
        String cacheKey;
        HttpParams httpParams = new HttpParams();
        cacheKey = url.concat(httpParams.toString());

        if (httpParamsArray != null)
            for (HttpParams h : httpParamsArray) {
                httpParams.put(h);
            }

        if (cacheMode == null)
            cacheMode = CacheMode.NO_CACHE;

        OkGo.<String>get(url).tag(url).cacheKey(cacheKey).cacheMode(cacheMode).params(httpParamsArray == null ? null : httpParams).execute(new StringCallback() {
            @Override
            public void onStart(Request<String, ? extends Request> request) {
                super.onStart(request);
                mView.onRequestNetResult(requestId, RequestResultState.onStart, null, null);
            }

            @Override
            public void onSuccess(Response<String> response) {
                mView.onRequestNetResult(requestId, RequestResultState.onSuccess, response.body(), response);
            }

            @Override
            public void onCacheSuccess(Response<String> response) {
                super.onCacheSuccess(response);
                onSuccess(response);
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                mView.onRequestNetResult(requestId, RequestResultState.onError, response.body(), response);
            }

            @Override
            public void onFinish() {
                super.onFinish();
                mView.onRequestNetResult(requestId, RequestResultState.onFinish, null, null);
            }
        });
    }
}
